package com.app.samba;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.app.samba.util.AppUtil;
import com.app.samba.util.FileUtils;
import com.app.samba.util.PermissionListener;
import com.app.samba.util.PermissionUtil;
import com.app.samba.util.RealPathFromUriUtils;
import com.app.samba.util.SambaNewUtil;
import com.app.samba.util.SambaUtil;
import com.app.samba.util.ToastUtil;

import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;

import static com.app.samba.DebugLog.SAMBA_LOG;

public class MainActivity extends AppCompatActivity {
    private Button btn01;
    private Button btn02;
    private Button btn03;
    private Button btn04;

    private String path; //路径
    String host = "192.168.31.1"; //samba--ip
    String filePathTwo = "/图片/sambaTest/宝宝/"; //文件夹下载 ..后面必须加  /
    String filePath = "/图片/3岁/01.jpg"; //单个文件下载
    // 单个文件下载
    public static SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS", Locale.CHINA);
    String uploadPath = "/图片/sambaTest/upload/"; //上传samba服务器的文件夹
    String fileName;
    private static final int REQUEST_PICK_IMAGE = 10086;
    private String realPathFromUri;
    private ImageView ivShow;
    String listPath = "/图片/sambaTest/"; //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn01 = findViewById(R.id.btn_01);
        btn02 = findViewById(R.id.btn_02);
        btn03 = findViewById(R.id.btn_03);
        btn04 = findViewById(R.id.btn_04);

        ivShow = findViewById(R.id.iv_iamge);
        path = FileUtils.ROOT_PATH + AppUtil.getPackageName(MainActivity.this) + FileUtils.HEAD_PATH;
        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImage();

            }
        });
        btn02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //单个文件下载
                        String remoutUrl = "smb://" + host + filePath;
                        download(remoutUrl, path);

                    }
                }).start();

            }
        });
        btn03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(realPathFromUri)) {
                    ToastUtil.toastShortContent(MainActivity.this, "请选择图片路径");
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.isEmpty(fileName)) {
                            fileName = getDateYYMMSS();
                        }
                        String remoutUrl = "smb://" + host + uploadPath;
                        uploadFile(remoutUrl);
                    }
                }).start();

            }
        });
        btn04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下载文件夹
                String remoutUrl = "smb://" + host + filePathTwo;
                downLoadTwo(remoutUrl, path);
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                showListFile();
            }
        }).start();

    }

    /**
     * 显示文件
     */
    private void showListFile() {
        String remoutUrl = "smb://" + host + listPath;
        try {
            List<Map<String, Object>> maps = SambaUtil.sambaFileListInfo(remoutUrl);
            for (int i = 0; i < maps.size(); i++) {
                Object o = maps.get(i).get("name");
                DebugLog.d(SAMBA_LOG+"名字 "+maps.get(i).get("name")+" 路径 "+maps.get(i).get("path"));
            }
        } catch (MalformedURLException | SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载单个文件
     *
     * @param remoutUrl
     * @param path
     */
    public void download(String remoutUrl, String path) {
        SmbFile remoteSmbFile = null;
        try {
            remoteSmbFile = new SmbFile(remoutUrl);
            DebugLog.d(SAMBA_LOG + "进入 update() ...." + " remoteUrl " + remoutUrl + " path " + path);
            SambaUtil.downloadFileFromSamba(remoteSmbFile, path);
        } catch (MalformedURLException | SmbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件夹
     *
     * @param remoutUrl
     * @param path
     */
    private void downLoadTwo(String remoutUrl, String path) {
        DebugLog.d(SAMBA_LOG + "进入 updateTwo() ...." + " remoteUrl " + remoutUrl + " path " + path);
        try {
            SambaNewUtil.download(remoutUrl, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传文件
     *
     * @param remoutUrl
     */
    private void uploadFile(String remoutUrl) {
        DebugLog.d(SAMBA_LOG + "进入 uploadFile()上传 ...." + " remoteUrl " + remoutUrl + " realPathFromUri " + realPathFromUri);
        try {
            SmbFile remoteSmbFile = new SmbFile(remoutUrl);
            SambaUtil.uploadFileToSamba(realPathFromUri, remoteSmbFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        fileName = realPathFromUri.substring(realPathFromUri.lastIndexOf("/") + 1, realPathFromUri.length());
                        showImage(realPathFromUri);
                        DebugLog.d(SAMBA_LOG + " realPathFromUri " + realPathFromUri);

                    } else {
                        ToastUtil.toastLongContent(this, "图片损坏，请重新选择");
                    }

                    break;
            }
        }
    }

    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ivShow.setImageBitmap(bm);

    }

    /**
     * 获取图片
     */
    @SuppressLint("ObsoleteSdkInt")
    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }
    }


    public String getDateYYMMSS() {
        return sdf.format(new Date());
    }

}
